package com.zzyl.nursing.service.impl;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;

import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaweiIotProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备Service业务层处理
 * 
 * @author wei
 * @date 2025-11-14
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private HuaweiIotProperties huaweiIotProperties;
    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device)?1:0;
    }


    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device)?1:0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备信息
     * 
     *
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteDeviceById( DeviceDto deviceDto)
    {

        // 使用 MyBatis-Plus 根据 iotId 删除
        boolean removed = remove(new LambdaQueryWrapper<Device>()
                .eq(Device::getIotId, deviceDto.getIotId())
        );
        if (!removed) {
            // 可选：记录日志或抛出异常（如设备不存在）
            throw new BaseException("设备id不存在，删除失败");
        }
        //删除成功后删除物联网设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(deviceDto.getIotId());

        try {
            client.deleteDevice(request);
        } catch (Exception ex) {
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }
        log.info("删除设备成功");
    }

    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        try {
            // 调用查询设备列表接口
            ListProductsResponse response = client.listProducts( request);
            // 1. 获取原始设备列表 JSON 数组
            JSONArray products = JSONUtil.parseArray(response.getProducts());

// 2. 遍历每个设备对象，将 productId 改为 productKey
            for (Object obj :   products) {
                JSONObject product = (JSONObject) obj;
                // 如果存在 productId，则重命名
                if (product.containsKey("productId")) {
                    String productId = product.getStr("productId");
                    product.set("productKey", productId); // 添加新字段
                    product.remove("productId");          // 删除旧字段
                }
                if (product.containsKey("name")) {
                    String productName = product.getStr("name");
                    product.set("productName", productName);
                    product.remove("name");
                }
            }

// 3. 转换为 JSON 字符串
            String jsonStr = JSONUtil.toJsonStr(products);

// 4. 存入 Redis
            redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, jsonStr);


            /*
            * 同步设备列表
            *
            * */

            ListDevicesRequest request1 = new ListDevicesRequest();
            ListDevicesResponse response1 = client.listDevices(request1);
            JSONArray devices = JSONUtil.parseArray(response1.getDevices());
            for (Object obj : devices) {

            }



        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }




    }

    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        //如果数据为空，则返回一个空集合
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        //解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        long count = count(queryWrapper);
        if(count > 0){
            throw new BaseException("设备名称已存在，请重新输入");
        }
        //保存设备到iot平台
        AddDeviceRequest registerDeviceRequest= deviceDto.getRegisterDeviceRequest();
        List<InitialDesired> listbodyShadow = new ArrayList<>();
        //获取产品信息
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(deviceDto.getProductKey());
        ShowProductResponse productResponse= client.showProduct(request);
        //从产品信息中获取服务id
        JSON json = JSONUtil.parse(productResponse.getServiceCapabilities().get(0));
        String serviceId = json.getByPath("serviceId").toString();
        //获取产品名称
         String productName = productResponse.getName();


        listbodyShadow.add(
                new InitialDesired()
                        .withServiceId(serviceId)
                        .withDesired("{\"BatteryPercentage\":\"60\",\"BodyTemp\":\"30\",\"BloodOxygen\":\"90\",\"HeartRate\":\"101\"}")
        );
        //添加设备认证信息
        //通过安全接入，密钥认证
        AuthInfo authInfobody = new AuthInfo();
        authInfobody.withAuthType("SECRET")
                .withSecureAccess(true);
        AddDevice body = new AddDevice();
         body.withShadow(listbodyShadow);
         body.withAppId("c4ff5f84cfbb414c844b85ea33786b82");
         body.withDescription("hh");
         body.withAuthInfo(authInfobody);
         body.withProductId(deviceDto.getProductKey());
         body.withDeviceName(deviceDto.getDeviceName());
         body.withNodeId(deviceDto.getDeviceName()+"_0304"+ RandomUtil.randomNumbers(4));

        registerDeviceRequest.withBody( body);
       AddDeviceResponse response;

       response = client.addDevice(registerDeviceRequest);


        //保存到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setProductName(productName);

        //物理位置
        if(device.getLocationType().equals(0)){
            device.setPhysicalLocationType(-1);
        }

        //补全设备id
        device.setIotId(response.getDeviceId());
        device.setNickName(deviceDto.getNickname());


        try {
            deviceMapper.insertDevice(device);
        } catch (Exception e) {

            //删除iot中的设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();

            deleteDeviceRequest.withDeviceId(response.getDeviceId());

            try {
                client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new BaseException("物联网接口 - 删除设备，调用失败");
            }
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
    }

    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {

        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId( deviceDto.getIotId());
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备，调用失败");
        }
      /*  response.getAuthInfo().getSecret();
        response.getDeviceName();
        response.getProductId();
        response.getProductName();
        response.getAuthInfo().getAuthType();
        response.getStatus();

        response.getActiveTime();
*/
        //查询表中的数据
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId,deviceDto.getIotId()));
        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);
        deviceVo.setDeviceSecret(response.getAuthInfo().getSecret());
        deviceVo.setStatus(response.getStatus());
        deviceVo.setGmtCreate(response.getCreateTime());
        deviceVo.setGmtActive(response.getActiveTime());



       return   deviceVo ;
    }
}
